package com.atguigu.gulimail.ware.service.impl;

import com.atguigu.common.constant.WareConstant;
import com.atguigu.gulimail.ware.entity.PurchaseDetailEntity;
import com.atguigu.gulimail.ware.service.PurchaseDetailService;
import com.atguigu.gulimail.ware.service.WareSkuService;
import com.atguigu.gulimail.ware.vo.MergeVo;
import com.atguigu.gulimail.ware.vo.PurchaseDoneVo;
import com.atguigu.gulimail.ware.vo.PurchaseItemDoneVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimail.ware.dao.PurchaseDao;
import com.atguigu.gulimail.ware.entity.PurchaseEntity;
import com.atguigu.gulimail.ware.service.PurchaseService;
import org.springframework.transaction.annotation.Transactional;

import javax.validation.constraints.NotNull;


@Service("purchaseService")
public class PurchaseServiceImpl extends ServiceImpl<PurchaseDao, PurchaseEntity> implements PurchaseService {

    @Autowired
    private PurchaseDetailService purchaseDetailService;
    @Autowired
    private WareSkuService wareSkuService;
    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<PurchaseEntity> page = this.page(
                new Query<PurchaseEntity>().getPage(params),
                new QueryWrapper<PurchaseEntity>()
        );

        return new PageUtils(page);
    }



    //查询未领取的采购单
    @Override
    public PageUtils queryPageUnreceive(Map<String, Object> params) {


        IPage<PurchaseEntity> page = this.page(
            new Query<PurchaseEntity>().getPage(params),
            //status为 0表示采购单刚新建  为1 表示采购单该分配某个人
            new QueryWrapper<PurchaseEntity>().eq("status",0).or().eq("status",1)
    );

        return new PageUtils(page);
    }

    //合并采购单实现方法
    @Transactional
    @Override
    public void mergePurchase(MergeVo mergeVo) {
        //获取采购单id
        Long purchaseId = mergeVo.getPurchaseId();
        //未创建采购单，进行判断，就创建一个采购单
        if(purchaseId == null){
            //创建采购单实例对象
            PurchaseEntity purchaseEntity = new PurchaseEntity();
            //采购单里面属性进行初始化
            purchaseEntity.setCreateTime(new Date());
            purchaseEntity.setUpdateTime(new Date());
            purchaseEntity.setStatus(WareConstant.PurchaseStatusEnum.CREATED.getCode());
            //新建的采购单保存到数据库中
            this.save(purchaseEntity);
            purchaseId = purchaseEntity.getId();
        }

        //TODO 确认采购单是0或者是1才能进行合并

        //前端传递过来的vo里面的item的采购单项进行合并
        //获取采购单项 合并的采购单项id
        List<Long> items = mergeVo.getItems();
        //创建一个已完成的合并的采购单id
        Long finalPurchaseId = purchaseId;
        //进行采购单项items进行流处理 获取到采购单详情
        List<PurchaseDetailEntity> collect = items.stream().map((i) -> {
            //创建采购单详情的实体
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            //采购单详情的id  采购单id  采购单详情的状态
            purchaseDetailEntity.setId(i);
            purchaseDetailEntity.setPurchaseId(finalPurchaseId);
            purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailsStatusEnum.ASSIGNED.getCode());
            return purchaseDetailEntity;
        }).collect(Collectors.toList());

        //合并的后的采购单的详情批量修改  保存到数据库中采购单详情表中
        purchaseDetailService.updateBatchById(collect);
        //合并完采购单，修改采购单时间
        //1创建采购单实例
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        //2设置采购单id  更新时间
        purchaseEntity.setId(purchaseId);
        purchaseEntity.setUpdateTime(new Date());
        this.updateById(purchaseEntity);
    }

    //领取采购单
    @Override
    public void received(List<Long> ids) {
        //1确认当前采购是新建或者已分配状态
        List<PurchaseEntity> collect = ids.stream().map(id -> {
            //根据id进行获取到采购单项
            PurchaseEntity purchaseEntity = this.getById(id);
            return purchaseEntity;
        }).filter(item -> {
            //过滤保留采购单 状态为新建和已分配，其他数据过滤掉
            if (item.getStatus() == WareConstant.PurchaseStatusEnum.CREATED.getCode() || item.getStatus() == WareConstant.PurchaseStatusEnum.ASSIGNED.getCode()) {
                return true;
            }
            //否则过滤掉
            return false;
        }).map(item -> {
            //采购单实体 设置采购单实体的状态:已领取 和修改时间当前修改时间
            item.setStatus(WareConstant.PurchaseStatusEnum.RECEIVE.getCode());
            item.setUpdateTime(new Date());
            return item;
        }).collect(Collectors.toList());
        //保存采购单的实体
        this.updateBatchById(collect);


        //3改变采购项的状态
        //遍历采购单的list容器
        collect.forEach(item -> {
            //根据采购单id获取采购项list容器
            List<PurchaseDetailEntity> entities = purchaseDetailService.listDetailByPurchaseId(item.getId());
            //跟新采购项中的状态为
            List<PurchaseDetailEntity> collect1 = entities.stream().map(entity -> {
                //创建采购项实例
                PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
                //设置采购项id,修改这个采购项
                purchaseDetailEntity.setId(entity.getId());
                //修改采购项的状态
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailsStatusEnum.BUYING.getCode());
                //返回采购项的实体
                return purchaseDetailEntity;
            }).collect(Collectors.toList());
            purchaseDetailService.updateBatchById(collect1);

        });
    }

    //完成采购
    @Transactional
    @Override
    public void done(PurchaseDoneVo doneVo) {
        //获取采购单id
        Long id = doneVo.getId();
        //2改变采购项目的状态
        //定义一个标志，false表示采购失败，true表示采购成功
        Boolean flag = true;
        //采购vo对象获取采购项list容器
        List<PurchaseItemDoneVo> items = doneVo.getItems();
        //创建一个采购详情的list容器
        List<PurchaseDetailEntity> updates = new ArrayList<>();
        //进行遍历采购项
        for (PurchaseItemDoneVo item : items) {
            //初始化一个采购详情实体实例
            PurchaseDetailEntity purchaseDetailEntity = new PurchaseDetailEntity();
            //进行判断采购项状态为有异常，标志值为false
            if(item.getStatus() == WareConstant.PurchaseDetailsStatusEnum.HASERR.getCode()){
                flag = false;
                //重新把当前状态设置到采购单中
                purchaseDetailEntity.setStatus(item.getStatus());
            }else{
                //采购成功
                //根据采购项id获取采购详情实体类
                PurchaseDetailEntity entity = purchaseDetailService.getById(item.getItemId());
                //添加库存 添加skuId的商品往wareId这个仓库添加数量为skuNum件商品
                wareSkuService.addStock(entity.getSkuId(),entity.getWareId(),entity.getSkuNum());
                //设置采购项的状态
                purchaseDetailEntity.setStatus(WareConstant.PurchaseDetailsStatusEnum.FINISH.getCode());
            }
            //采购详情设置采购项的id
            purchaseDetailEntity.setId(item.getItemId());
            //采购项添加库存
            updates.add(purchaseDetailEntity);

        }
        //批量进行更新
        purchaseDetailService.updateBatchById(updates);
        //修改采购单的状态
        //1创建采购单是实例对象
        PurchaseEntity purchaseEntity = new PurchaseEntity();
        //2设置采购单id
        purchaseEntity.setId(id);
        //根据采购项的状态 进行设置采购单的状态
        //如果采购项为采购完成，设置采购单采购完成 否则采购单状态设置异常
        purchaseEntity.setStatus(flag?WareConstant.PurchaseStatusEnum.FINISH.getCode():WareConstant.PurchaseStatusEnum.HASERR.getCode());
        //设置采购单更新时间
        purchaseEntity.setUpdateTime(new Date());
        //保存在数据库中
        this.updateById(purchaseEntity);

    }

}